package com.web.cms.pan.provider;

import com.blue.integration.serve.Bucket;
import com.blue.integration.serve.StorageClient;
import com.blue.jdbc.Page;
import com.blue.validation.spi.IdListValidator;
import com.web.cms.pan.exception.FileDataException;
import com.web.cms.pan.facade.DeleteFileDataFacade;
import com.web.cms.pan.message.DeleteFileDataRequest;
import com.web.cms.pan.message.DeleteFileDataResponse;
import com.web.cms.pan.model.DeleteFileData;
import com.web.cms.pan.service.DeleteFileDataService;
import com.web.cms.pan.util.DeleteFileDataConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhengjin
 * @since 1.0 2018年05月02日
 */
@Component("/panDeleteFileDataProvider")
public class DeleteFileDataProvider implements DeleteFileDataFacade
{
	@Autowired
	private DeleteFileDataService deleteFileDataService;
	@Autowired
	private StorageClient storageClient;

	public DeleteFileDataProvider()
	{
	}

	@Override
	public Page<DeleteFileDataResponse> listPage(DeleteFileDataRequest request, int start, int size)
	{
		DeleteFileData deleteFileData = DeleteFileDataConvertor.toDeleteFileData(request);
		Page<DeleteFileData> page = new Page<>(size);
		page.setCurPage(start);
		page = deleteFileDataService.list(deleteFileData, page);
		Page<DeleteFileDataResponse> responsePage = DeleteFileDataConvertor.toResponse(page, storageClient);
		return responsePage;
	}

	@Override
	public void delete(String ids)
	{
		if (ids == null || ids.isEmpty() || !IdListValidator.isValid(ids))
			throw new FileDataException("文件ID列表格式错误");

		List<Integer> idList = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
		Map<Integer, DeleteFileData> map = deleteFileDataService.getList(idList);
		List<Integer> deleteIdList = new ArrayList<>();
		for (Map.Entry<Integer, DeleteFileData> entry : map.entrySet())
		{
			storageClient.delete(Bucket.PAN, entry.getValue().getKey());
			deleteIdList.add(entry.getKey());
		}
		deleteFileDataService.delete(deleteIdList);
	}

}
